import busAdd from './src/addBus'
import dataAdd from './src/addData'
import creatProxyFun from './src/creatProxy'
const storeArr = [], asyncStore = {}
class rStore {
    constructor(Setting, storeName) {
        this.storeName = storeName || undefined
        let Data = {}, options
        if (Setting) {
            Data = Setting.Data
            options = Setting.options
        }
        let busOptions = true, dataOptions = true;
        if (Data && typeof Data !== 'object') {
            throw 'The initialization data of data must be of object type'
        }
        if (options) {
            if (typeof options.bus === 'object' || typeof options.bus === 'boolean') busOptions = options.bus
            if (typeof options.data === 'object' || typeof options.data === 'boolean') dataOptions = options.data
        }
        this.stateID = storeArr.length
        storeArr.push(this)
        const storeKeys = Object.keys(asyncStore)
        storeArr.forEach(itemStore => {
            storeKeys.forEach(itemAsyncStoreName => {
                if (itemStore.storeName === itemAsyncStoreName) {
                    asyncStore[itemAsyncStoreName]._resolve(itemStore)
                }
            })
        })
        busAdd(this, busOptions)
        dataAdd(this, Data, dataOptions)
    }
}

const creatRStore = (newStore) => {
    if (!newStore) return new rStore()
    const storeOptions = { options: {} }
    if (newStore.offStore) storeOptions.options.data = false
    if (newStore.offBus) storeOptions.options.bus = false
    if (newStore.data || typeof newStore.data === 'object') storeOptions.Data = newStore.data
    const store = new rStore(storeOptions, newStore.name || undefined)
    if (newStore.actions && typeof newStore.actions === 'function') {
        const result = newStore.actions(store)
        if (typeof result === 'object') {
            store.actions = result
        }
    }
    return store
}

const getRStore = async (storeName) => {
    const result = storeArr.find(item => item.storeName === storeName)
    if (typeof result === 'object') {
        asyncStore[storeName] ? delete (asyncStore[storeName]) : ''
        return result
    }
    if (!asyncStore[storeName]) {
        asyncStore[storeName] = {}
        asyncStore[storeName]._promise = new Promise((resolve) => {
            asyncStore[storeName]._resolve = resolve
        })
    }
    return await asyncStore[storeName]._promise
}
const creatProxy = creatProxyFun(storeArr)
export {
    getRStore, creatProxy, creatRStore,
}